import wepy from 'wepy'

export default {
  host: 'http://api.rongsue.com',
  ajax: function(obj) {
    let sendObj = {
      url: this.host + obj.url,
      data: obj.data,
      method: (obj.type) ? obj.type.toUpperCase() : 'GET',
      header: {
        Authorization: 'Bearer ' + wepy.getStorageSync('token')
      },
      dataType: 'json'
    }

    return wepy.request(sendObj).catch((e) => { console.log(e); if (obj.error) { obj.error(e) } })
  },
  getQuery: function () {
    // <<Professional JavaScript for Web Developers>> param BOM

    let qs = location.search.length > 0 ? location.search.substring(1) : ''
    let args = {}
    let items = qs.length ? qs.split('&') : []
    let item = null
    let name = null
    let value = null
    let i = 0
    let len = items.length

    for (i = 0; i < len; i++) {
      item = items[i].split('=')
      name = decodeURIComponent(item[0])
      value = decodeURIComponent(item[1])

      if (name.length) {
        args[name] = value
      }
    }
    return args
  },
  obj2query: function (obj) {
    var queryString = ''
    for (var item in obj) {
      queryString += '&' + item + '=' + obj[item].toString()
    }
    queryString = '?' + queryString.substring(1)
    return queryString
  }
}
